package homework.job4

import akka.actor.{Actor, ActorRef}

import scala.collection.mutable.HashMap

class Master extends Actor{

  //串讲一个hashmap来保存对象 map【actorname, (上次心跳的时间，Ref)】
  private val hashMap = new HashMap[String, Tuple2[Long, ActorRef]]


  override def receive: Receive = {
    case "start" => checkSlaver()//启动定时任务查询slaver心跳情况
    case "heart" => {
      val ref: ActorRef =sender()
      hashMap+=(ref.toString()->(System.currentTimeMillis(),ref))
    }//收到心跳
  }

  def checkSlaver(): Unit ={
    //获取到当前时间
    while (true){
    val current=System.currentTimeMillis()
    //60秒内都没有发送心跳的slave 踢出
    for ((k,(v1,v2)) <- hashMap if current-v1<60*1000){
      hashMap -= (k)
      v2 ! "exit"
    }
      Thread.sleep(60*1000)
    }
  }

}
